package com.cykj.web.controller.posbiz;

import com.alibaba.fastjson.JSONObject;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.core.domain.model.LoginUser;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.common.utils.ServletUtils;
import com.cykj.common.utils.poi.ExcelUtil;
import com.cykj.framework.web.service.TokenService;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.BizMercahntFeeNameDTO;
import com.cykj.pos.domain.vo.BizPosMachineVo;
import com.cykj.pos.mapper.BizMerchantInfoMapper;
import com.cykj.pos.mapper.BizPosMachineMapper;
import com.cykj.pos.profit.dto.VueCallBack;
import com.cykj.pos.service.IBizPosMachineService;
import com.cykj.pos.service.IUnFailureActiveTemplateService;
import com.cykj.pos.util.HttpUtil;
import io.swagger.annotations.ApiOperation;
import javafx.geometry.Pos;
import lombok.RequiredArgsConstructor;
import org.omg.CORBA.FREE_MEM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/notoken" )
public class BizStorageEquipmentController {

    private final IBizPosMachineService posMachineService;

    private final BizPosMachineMapper posMachineMapper;

    private final IBizPosMachineService iBizPosMachineService;
    @Autowired
    private TokenService tokenService;
    @Resource
    private BizMerchantInfoMapper bizMerchantInfoMapper;
    private final com.cykj.pos.domain.PosPCommonParamConfig PosPCommonParamConfig;
    @Value("${posp.url.merchant}")
    private String merchant;
    @Value("${posp.url.merchantFlow}")
    private String merchantFlow;

    @Resource
    private IUnFailureActiveTemplateService iUnFailureActiveTemplateService;

    @GetMapping("/getManufacturer")
    @ApiOperation("获取制造商")
    public AjaxResult getManufacturer(){
       AjaxResult ajaxResult = AjaxResult.success();
      List<StorageEquipment> list = posMachineService.getManufacturer();
      ajaxResult.put("list",list);
       return ajaxResult;
    }
    @ApiOperation("获取设备型号")
    @GetMapping("/getManufacturerModel/{id}")
    public AjaxResult getManufacturerModel(@PathVariable Long id){
       AjaxResult ajaxResult = AjaxResult.success();
      List<StorageEquipment> list = posMachineService.getManufacturerModel(id);
      ajaxResult.put("list",list);
       return ajaxResult;
    }
    @ApiOperation("获取服务费")
    @GetMapping("/getServiceCharge/{id}")
    public AjaxResult getServiceCharge(@PathVariable Long id){
       AjaxResult ajaxResult = AjaxResult.success();
      List<StorageEquipment> list = posMachineService.getServiceCharge(id);
      ajaxResult.put("data",list);
       return ajaxResult;
    }

    @ApiOperation("/设备修改")
    @PostMapping("/updateEquipment")
    public AjaxResult updateEquipment(@RequestBody PospPosmachine PospPosmachine){
       int i = posMachineService.updateEquipment(PospPosmachine);
       if (i>0){
           return AjaxResult.success("修改成功");
       }else {
           return AjaxResult.error("修改失败");
       }

    }

    @ApiOperation("/嘉联修改押金")
    @PostMapping("/jlUpdateDep")
    public AjaxResult jlUpdateDep(@RequestBody PospPosmachine PospPosmachine){
        return posMachineService.jlUpdateDep(PospPosmachine);

    }

    @GetMapping(value = "/getPosCodeInfo/{posCode}")
    public AjaxResult getPosCodeInfo(@PathVariable("posCode" ) String posCode){
        AjaxResult ajaxResult = AjaxResult.success();
        PospPosmachine posCodeInfo =  posMachineService.getPosCodeInfo(posCode);
        ajaxResult.put("data",posCodeInfo);
        return ajaxResult;
    }



    /**
     * posp设备入库
     * @param PospPosmachine
     * @return
     */
    @Transactional
    @PostMapping("/posp/storage/equipment")
    public AjaxResult storageEquipmentToPosp(@RequestBody PospPosmachine PospPosmachine){
        if("17".equals(PospPosmachine.getChannel())){
            if(PospPosmachine.getFeeId() == null){
                return AjaxResult.error("嘉联渠道费率必填");
            }
        }
        BizPosMachine bizPosMachine1 = posMachineService.selectPosBySnCode(PospPosmachine.getPosSn());
        if (bizPosMachine1 != null){
            return AjaxResult.error("已存在该设备");
        }
        String  posModel =   posMachineService.getUnitType(PospPosmachine.getPosModel());
        PospPosmachine.setPosSn(PospPosmachine.getPosSn().replace(" ",""));
        PospPosmachine.setPosSn(PospPosmachine.getPosSn().toUpperCase());
//        if("2".equals(PospPosmachine.getChannel())){
//            //存本地
//            BizPosMachine bizPosMachine = new BizPosMachine();
//            bizPosMachine.setMerchId(Long.parseLong(PospPosmachine.getMerchName()));
//            String posTypeName = posMachineMapper.selectPosType(PospPosmachine.getPosTypeId());
//            bizPosMachine.setPosType(PospPosmachine.getPosTypeId());
//            bizPosMachine.setPosName(posTypeName);
//            bizPosMachine.setMerchId(Long.parseLong(PospPosmachine.getMerchName()));
//            bizPosMachine.setPosCode(PospPosmachine.getPosSn());
//            bizPosMachine.setDeviceType(posModel);
//            bizPosMachine.setCreateTime(new Date());
//            bizPosMachine.setModelId(PospPosmachine.getPosModel());
//            bizPosMachine.setSimAmt(PospPosmachine.getFlowAmount().toString());
//            bizPosMachine.setSimDaynum(PospPosmachine.getSimDaynum());
//            bizPosMachine.setManufacturersId(PospPosmachine.getPosName());
//            bizPosMachine.setSimIccid(PospPosmachine.getSimIccid());
//            bizPosMachine.setDevImei(PospPosmachine.getDevImei());
//            bizPosMachine.setVar5(PospPosmachine.getFrozenAmount().toString());  //押金
//            bizPosMachine.setChannel(PospPosmachine.getChannel());
//            bizPosMachine.setCustomerCashBackId(PospPosmachine.getTemp3());
//            bizPosMachine.setTemp1(PospPosmachine.getTemp1());
//            bizPosMachine.setTemp2(PospPosmachine.getTemp2());
//            iBizPosMachineService.save(bizPosMachine);
//            bizPosMachine.setAgentid(this.agentid());
//            String str = HttpUtil.doPostxxl(this.merchant, JSONObject.toJSONString(bizPosMachine));
//            JSONObject jsonObject1 = JSONObject.parseObject(str);
//            System.out.println(jsonObject1.toJSONString());
//            if("500".equals(jsonObject1.getString("code"))){
//                return AjaxResult.error(jsonObject1.getString("msg"));
//            }
//            return  AjaxResult.success("入库成功");
//        }
        Map<String, Object> data = new HashMap<String, Object>();

        data.put("posName", "1".equals(PospPosmachine.getPosName())?"11" : PospPosmachine.getPosName());
        data.put("posModel", "1".equals(PospPosmachine.getPosModel()) ? "17":PospPosmachine.getPosModel());

        //查询制造商
        data.put("posSn", PospPosmachine.getPosSn());

        data.put("merchName", PospPosmachine.getMerchName());
        data.put("channel", PospPosmachine.getChannel());
        data.put("frozenAmount", PospPosmachine.getFrozenAmount());
        data.put("flowAmount", PospPosmachine.getFlowAmount());
        String posTypeId = PospPosmachine.getPosTypeId();
        if("0".equals(PospPosmachine.getPosTypeId())){
            posTypeId = "33";
        }else if("1".equals(PospPosmachine.getPosTypeId())){
            posTypeId = "34";
        }else if("2".equals(PospPosmachine.getPosTypeId())){
            posTypeId = "35";
        }
        data.put("posTypeId", posTypeId);
        data.put("simIccid", PospPosmachine.getSimIccid());
        data.put("devImei", PospPosmachine.getDevImei());
        data.put("simDaynum", PospPosmachine.getSimDaynum());
        data.put("agentid", "ANXINFU");
        data.put("toShqy", PospPosmachine.getToShqy());
        data.put("fee",PospPosmachine.getFeeId());
        System.out.println("请求参数--》》》》"+ JSONObject.toJSONString(data));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getEquipment(), JSONObject.toJSONString(data));
        System.out.println("设备入库返回参数"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("code") == 200){  //成功 执行自己的业务
            BizPosMachine bizPosMachine = new BizPosMachine();
            bizPosMachine.setMerchId(Long.parseLong(PospPosmachine.getMerchName()));
            String posTypeName = posMachineMapper.selectPosType(PospPosmachine.getPosTypeId());
            bizPosMachine.setPosType(PospPosmachine.getPosTypeId());
            bizPosMachine.setPosName(posTypeName);
            bizPosMachine.setMerchId(Long.parseLong(PospPosmachine.getMerchName()));
            bizPosMachine.setPosCode(PospPosmachine.getPosSn());
            bizPosMachine.setDeviceType(posModel);
            bizPosMachine.setCreateTime(new Date());
            bizPosMachine.setModelId(PospPosmachine.getPosModel());
            bizPosMachine.setSimAmt(PospPosmachine.getFlowAmount().toString());
            bizPosMachine.setSimDaynum(PospPosmachine.getSimDaynum());
            bizPosMachine.setManufacturersId(PospPosmachine.getPosName());
            bizPosMachine.setSimIccid(PospPosmachine.getSimIccid());
            bizPosMachine.setTerminalNo(jsonObject.getString("data"));
            bizPosMachine.setDevImei(PospPosmachine.getDevImei());
            bizPosMachine.setDevImei(PospPosmachine.getDevImei());
            bizPosMachine.setVar5(PospPosmachine.getFrozenAmount().toString());  //押金
            bizPosMachine.setChannel(PospPosmachine.getChannel());
            bizPosMachine.setCustomerCashBackId(PospPosmachine.getTemp3());
            bizPosMachine.setTemp1(PospPosmachine.getTemp1());
            bizPosMachine.setTemp2(PospPosmachine.getTemp2());
            bizPosMachine.setFee(String.valueOf(PospPosmachine.getFeeId()));
            bizPosMachine.setFlowLoop(PospPosmachine.getFlowLoop());
            bizPosMachine.setNextFlowDays(PospPosmachine.getNextFlowDays());
            iBizPosMachineService.save(bizPosMachine);
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }
    private String agentid(){
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        String suffix=bizMerchantInfoMapper.getSuffix(sysUserman.getUserId());
        return bizMerchantInfoMapper.getAgentId(suffix);
    }

    /**
     * 导入
     * @param
     * @return
     */
    @PostMapping("/pospsInsert")
    public AjaxResult pospsInsert(@PathVariable("file") MultipartFile file,
                                  boolean updateSupport,String merchName,String posTypeId,String posName,
                                  String deviceType,Integer type,String channel,Long temp3,Long feeId,Long temp1,
                                  Long temp2,String toShqy,String flowLoop,int nextFlowDays) throws Exception
    {

        if(temp1 == 1)temp1 = null;// 不选政策特殊处理
        if(temp2 == 2)temp2 = null;// 不选政策特殊处理
        if(temp3 == 1)temp3 = null;// 不选政策特殊处理
        if(feeId == 10000) feeId = null;// 不选政策特殊处理
        AjaxResult resultBack = new AjaxResult();
        ExcelUtil<BizPosMachineVo> util = new ExcelUtil<BizPosMachineVo>(BizPosMachineVo.class);
        List<BizPosMachineVo> posList = util.importExcel(file.getInputStream());
        if(posList.size() < 0){
            resultBack.put("code",500);
            resultBack.put("msg","未检测到文件内数据");
            return resultBack;
        }
        int seccess = 0;
        int failure = 0;
        int total = posList.size();
        StringBuilder msgDa =  new StringBuilder();
        if(type==3){//批量回调
            for (BizPosMachineVo vo:posList){
                    try{
                    int back=iBizPosMachineService.doCallBack(vo.getSn());
                    if(back>0){
                        seccess++;
                    }else{
                        failure++;
                        msgDa.append(vo.getSn().trim()).append(",");
                    }
                }catch(Exception e){
                    System.out.println("失败数据"+vo.getSn());
                    failure++;
                    msgDa.append(vo.getSn().trim()).append(",");
                }
            }
        }else if (type==4){
            if(merchName.equals("undefined")){
                resultBack.put("code",500);
                resultBack.put("msg","所属伙伴不能为空");
                return resultBack;
            }
            for (BizPosMachineVo vo:posList){
                try{
                    Long merchId=Long.parseLong(merchName);
                    VueCallBack vueCallBack1=new VueCallBack();
                    vueCallBack1.setMerchId(merchId);
                    vueCallBack1.setPosCode(vo.getSn());
                    int CallBack=iBizPosMachineService.doTransfers(vueCallBack1);
                    if(CallBack>0){
                        seccess++;
                    }else{
                        failure++;
                        msgDa.append(vo.getSn().trim()).append(",");
                    }
                }catch(Exception e){
                    e.printStackTrace();
                    System.out.println("失败数据"+vo.getSn());
                    failure++;
                    msgDa.append(vo.getSn().trim()).append(",");
                }
            }

        }else{
            if(merchName.equals("undefined")){
                resultBack.put("code",500);
                resultBack.put("msg","所属伙伴不能为空");
                return resultBack;
            }
            if(posTypeId.equals("undefined")){
                resultBack.put("code",500);
                resultBack.put("msg","所属设备类型不能为空");
                return resultBack;
            }
            if(posName.equals("undefined")){
                resultBack.put("code",500);
                resultBack.put("msg","制造商不能为空");
                return resultBack;
            }
            if(deviceType.equals("undefined")){
                resultBack.put("code",500);
                resultBack.put("msg","设备型号不能为空");
                return resultBack;
            }
            if("17".equals(channel)){
                if(feeId == null){
                    return AjaxResult.error("导入失败:嘉联渠道费率必填");
                }
            }
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            PospPosmachine pospPosmachine = new PospPosmachine();
            for(BizPosMachineVo vo : posList){
                try{
                    pospPosmachine.setMerchName(merchName);
                    pospPosmachine.setPosTypeId(posTypeId);
                    pospPosmachine.setPosName(posName);
                    pospPosmachine.setPosModel(deviceType);
                    pospPosmachine.setPosSn(vo.getSn().trim());
                    pospPosmachine.setFrozenAmount(new BigDecimal(vo.getServiceFee().trim()));
                    pospPosmachine.setFlowAmount(new BigDecimal(vo.getFlowFee().trim()));
                    pospPosmachine.setSimDaynum(vo.getDate().trim());
                    pospPosmachine.setSimIccid("");
                    pospPosmachine.setDevImei("");
                    pospPosmachine.setTemp1(temp1);
                    pospPosmachine.setTemp2(temp2);
                    pospPosmachine.setTemp3(temp3);
                    pospPosmachine.setToShqy(toShqy);
                    pospPosmachine.setFeeId(feeId);
                    pospPosmachine.setFlowLoop(flowLoop);
                    pospPosmachine.setNextFlowDays(nextFlowDays);
                    AjaxResult result=new AjaxResult();
                    if(type==1){//新增
                        if(null==channel|| "".equals(channel)){
                            resultBack.put("code",500);
                            resultBack.put("msg","所属伙伴不能为空");
                            return resultBack;
                        }
                        pospPosmachine.setChannel(channel);
                        result= storageEquipmentToPosp(pospPosmachine);
                    }else if (type==2){//修改
                        result= updateEquipment(pospPosmachine);
                    }

                    if(result.get("code").equals(200)){
                        seccess++;
                    }else{
                        failure++;
                        msgDa.append(vo.getSn().trim()).append(",");
                    }
                }catch(Exception e){
                    System.out.println("失败数据"+vo.getSn());
                    failure++;
                    msgDa.append(vo.getSn().trim()).append(",");
                }

            }
        }


        resultBack.put("code",200);
        resultBack.put("successCount",seccess);
        resultBack.put("failureCount",failure);
        resultBack.put("total",total);
        resultBack.put("msg","共执行"+total+"条数据,"+seccess+"条成功,"+failure+"条失败:失败SN:"+msgDa);
        return resultBack;
    }
    /**
     * 批量设置流量费
     * @param
     * @return
     */
    @PostMapping("/pospsInsertFlow")
    public AjaxResult pospsInsertFlow(@PathVariable("file") MultipartFile file,
                                  boolean updateSupport,String merchName,String posTypeId,String posName,String deviceType,Integer type,String channel) throws Exception
    {
        AjaxResult resultBack = new AjaxResult();
        ExcelUtil<BizPosMachineVo> util = new ExcelUtil<BizPosMachineVo>(BizPosMachineVo.class);
        List<BizPosMachineVo> posList = util.importExcel(file.getInputStream());
        if(posList.size() < 0){
            resultBack.put("code",500);
            resultBack.put("msg","未检测到文件内数据");
            return resultBack;
        }
        int seccess = 0;
        int failure = 0;
        int total = posList.size();
        StringBuilder msgDa =  new StringBuilder();

        for (BizPosMachineVo vo:posList) {
            BizMerchantInfo infoVo= bizMerchantInfoMapper.selectMerchantInfoBySn(vo.getSn());
            if(null==infoVo){
                msgDa.append(vo.getSn().trim()).append(",");
                failure++;
            }else{
                JSONObject legalPerson = new JSONObject();
                legalPerson.put("flowAmount",vo.getFlowFee().trim());
                legalPerson.put("posCode",vo.getSn());
                legalPerson.put("merchantCode",infoVo.getMerchantCode());
                legalPerson.put("agentId",this.agentid());
                System.out.println("批量创建流量费："+JSONObject.toJSONString(legalPerson));
                String str = HttpUtil.doPostxxl(this.merchantFlow, JSONObject.toJSONString(legalPerson));
                JSONObject jsonObject = JSONObject.parseObject(str);
                String code = jsonObject.getString("code");
                String msg = jsonObject.getString("msg");
                if("500".equals(code)){
                    msgDa.append(vo.getSn().trim()).append(msg).append(",");
                    failure++;
                }else{
                    if(type==2){
                        bizMerchantInfoMapper.insertNoback(vo.getSn());
                    }
                    seccess++;
                }
            }
        }
        resultBack.put("code",200);
        resultBack.put("successCount",seccess);
        resultBack.put("failureCount",failure);
        resultBack.put("total",total);
        resultBack.put("msg","共执行"+total+"条数据,"+seccess+"条成功,"+failure+"条失败:失败SN:"+msgDa);
        return resultBack;
    }

    //未激活政策
    @PostMapping("/getUnActiveList")
    public AjaxResult unActiveList(){
        return iUnFailureActiveTemplateService.unActiveList();
    }

    //伪激活政策
    @PostMapping("/getFaActiveList")
    public AjaxResult faActiveList(){
        return iUnFailureActiveTemplateService.faActiveList();
    }

    //伪激活政策
    @PostMapping("/getCustomerCashBackList")
    public AjaxResult customerCashBackList(){
        return iUnFailureActiveTemplateService.customerCashBackList();
    }

    @GetMapping("/getFeeIdList")
    @ApiOperation("获取嘉联费率")
    public AjaxResult getFeeIdList(){
        AjaxResult ajaxResult = AjaxResult.success();
        List<BizMercahntFeeNameDTO> list = posMachineService.echoFeeId5563();
        ajaxResult.put("list",list);
        return ajaxResult;
    }


}
